﻿using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Web;
using System.Web.Http;
using System.Web.Http.Results;
using WPS.Log;
using WPS.Model;

namespace WPS.Web.Controllers
{
    public class WPSUserController : ApiController
    {
        #region 获取用户信息
        [HttpPost, Route("v1/3rd/user/info")]
        public JsonResult<JObject> WPSUserInfo()
        {
            LogHelper.Info("进入v1/3rd/user/info");
            JObject jsonObject = new JObject();
            JArray jsonArray = new JArray();
            JObject user = new JObject();
            try
            {
                string token = string.Empty;
                HttpContextBase httpContextBase = (HttpContextBase)Request.Properties["MS_HttpContext"];
                if (httpContextBase == null)
                {
                    return null;
                }
                HttpRequestBase request = httpContextBase.Request;
                if (request.Headers["x-wps-weboffice-token"] != null)
                {
                    token = request.Headers["x-wps-weboffice-token"].ToString();
                }

                String xmlString = null;

                using (StreamReader reader = new StreamReader(request.InputStream, Encoding.UTF8))
                {
                    xmlString = reader.ReadToEnd();
                }

                LogHelper.Info("stream："+ xmlString);
                if (request["ids"] != null)
                {
                    LogHelper.Info("id：" + request["ids"]);
                    string[] userIds = request["ids"].Split(',');
                    using (WPSModel context = new WPSModel())
                    {
                        WPSUserInfo userModel = null;
                        foreach (string userId in userIds)
                        {
                            userModel = context.WPSUserInfo.Where(u => u.ID == userId).FirstOrDefault();
                            user.Add("id", userModel.ID);
                            user.Add("name", userModel.NAME);
                            user.Add("permission", userModel.PERMISSION);
                            user.Add("avatar_url", userModel.AVATAR_URL);
                            jsonArray.Add(user);
                        }
                        jsonObject.Add("users", jsonArray);
                    }
                }
            }
            catch (Exception e)
            {
                throw new Exception(e.Message);
            }
            LogHelper.Info("users：" + jsonObject.ToString());
            LogHelper.Info("离开v1/3rd/user/info");
            return Json(jsonObject);
        }
        #endregion
    }
}
